# import yfinance as yf
# import pandas as pd
#
# tickers =  ['600000.SS']
#
# df = yf.download(tickers, start="2022-01-01", end="2022-12-31", group_by='ticker')
#
# print(df)

import base64
import baostock as bs
import requests
from datetime import date,timedelta

username = 'script'
password = '123456a.'

# bct服务
#bct_url = "http://10.1.6.61"
bct_url = "http://10.1.6.47"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69 '
today = str(date.today())
# today = '2023-04-07'
start_date = '2023-01-01'
end_date = today
instruments = [
    {'exchange':'sh','instrmentId':'000016'},
     #  {'exchange':'sh','instrmentId':'000852'},
     # {'exchange':'sh','instrmentId':'000300'},
     # {'exchange':'sh','instrmentId':'000905'}

    # {'exchange':'sh','instrmentId':'510500'}
    # {'exchange':'sz','instrmentId':'512690'}

]


# 获得对应token
def saveBct(token, data_list):
    for data in data_list:
        headers = {"Authorization": "Bearer " + token}
        json = {"instance": "close", "instrumentId": data[2], "valuationDate": data[0], "quote": {"close": data[1]}}
        # 获得json 数据
        r = requests.post(url=bct_url + '/bct/market-data-service/quote/save',
                          json=json, headers=headers)
        print(r.json())


def saveQ():

    lg = bs.login()
    # 参数设置
    token = _get_token(username, password, bct_url)
    for instrument in instruments:

        print(today)
        rs = bs.query_history_k_data_plus(instrument.get("exchange")+"."+instrument.get("instrmentId"),
                                          "date,close",
                                          start_date=start_date, end_date=end_date,
                                          frequency="d", adjustflag="3")
        data_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录，将记录合并在一起
            quote_data = rs.get_row_data()
            quote_data.append(instrument.get("instrmentId") + "."+instrument.get("exchange").upper())
            data_list.append(quote_data)
        saveBct(token,data_list)



# 接口响应参数json化
def _get_token(auth_username: str, auth_password: str, server_url: str,
               base64_encode: bool = True) -> str:
    auth_url = "%s%s" % (server_url, '/api/auth-service/users/login')
    if base64_encode:
        usr_name = base64.b64encode(auth_username.encode())
        usr_pwd = base64.b64encode(auth_password.encode())
    else:
        usr_name = auth_username
        usr_pwd = auth_password

    auth_body = {
        'userName': usr_name.decode(),
        'password': usr_pwd.decode()
    }
    headers = {'User-Agent': user_agent}
    auth = requests.post(auth_url, json=auth_body, headers=headers)
    try:
        _token = auth.json()['token']
        return _token
    except Exception:
        error_message = auth.json()['errorMessage']
        raise ValueError(error_message)

if __name__ == '__main__':
    saveQ()